//
//  BFGridItem.m
//  13KModel
//
//  Created by jack on 1/09/12.
//  Copyright (c) 2012 butterfly. All rights reserved.
//
// CLASS INCLUDES
#import "BFGridItem.h"

// SYSTEM INCLUDES
#import <QuartzCore/QuartzCore.H>

// CONST DEFINE
CGFloat const kDelButtonWidth = 20.0f;
CGFloat const kDelButtonHight = 20.0f;
CGFloat const kTextLabelHight = 20.0f;
CGFloat const kTextLeftMargin = 20.0f;
CGFloat const kTextLabelRadius = 5.0f;

@interface BFGridItem()
@property (assign, nonatomic) CGPoint pressPoint;

- (void)clickGridItem:(id)sender;
- (void)longPressGridItem:(UILongPressGestureRecognizer*)sender;
@end

@implementation BFGridItem
@synthesize pressPoint;
@synthesize isEditing, isRemovable, index, section, delegate;

- (id)initWithTitle:(NSString*)title imageName:(NSString*)name
            section:(NSInteger)aSection atIndex:(NSInteger)aIndex editable:(BOOL)removable
{
    self = [super init];
    if (self) {
        // 基本属性设置
        self.index = aIndex;
        self.section = aSection;
        self.isEditing = NO;
        self.isRemovable = removable;
        self.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0.8];
        
        // 图片显示
        entry = [UIButton buttonWithType:UIButtonTypeCustom];
        [entry setBackgroundColor:[UIColor clearColor]];
        [entry setBackgroundImage:[UIImage imageNamed:name] forState:UIControlStateNormal];
        [entry addTarget:self action:@selector(clickGridItem:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:entry];
        
        // 
        labelText = [[UILabel alloc] initWithFrame:CGRectZero];
        labelText.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.6];
        labelText.text = [NSString stringWithFormat:@"%@ ", title];
        labelText.textColor = [UIColor whiteColor];
        labelText.textAlignment = UITextAlignmentRight;
//        [self addSubview:labelText];
        
        // 长按删除
//        UILongPressGestureRecognizer *longPressGesture = [[UILongPressGestureRecognizer alloc] 
//                                                          initWithTarget:self
//                                                          action:@selector(longPressGridItem:)];
//        [self addGestureRecognizer:longPressGesture];
//        
        // 是否支持删除
        [self setIsRemovable:removable];
    }
    
    return self;
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    // 始终覆盖VIEW
    if (!CGRectEqualToRect(entry.frame, self.bounds)) {
        entry.frame = CGRectMake(5, 5, self.bounds.size.width-10, self.bounds.size.height-10);
        
        // 标题文字显示区域
        CGSize textSize = [labelText.text sizeWithFont:labelText.font];
        if (textSize.width > self.bounds.size.width-kTextLeftMargin) {    
            labelText.frame = CGRectMake(kTextLeftMargin+10,
                                         self.bounds.size.height-kTextLabelHight, 
                                         self.bounds.size.width-kTextLeftMargin-10, 
                                         kTextLabelHight);
        }
        else {
            labelText.frame = CGRectMake(self.bounds.size.width-textSize.width,
                                         self.bounds.size.height-kTextLabelHight, 
                                         textSize.width, 
                                         kTextLabelHight);    
        }
    }
}

- (void)setIsRemovable:(BOOL)removable
{
    isRemovable = removable;
    if (isRemovable && !deleteBtn) {        
        deleteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [deleteBtn setFrame:CGRectMake(0, 0, kDelButtonWidth, kDelButtonHight)];
        [deleteBtn setImage:[UIImage imageNamed:@"deleteBtn.png"] 
                   forState:UIControlStateNormal];
        deleteBtn.backgroundColor = [UIColor clearColor];
        [deleteBtn addTarget:self action:@selector(removeButtonClicked:) 
            forControlEvents:UIControlEventTouchUpInside];
        [deleteBtn setHidden:YES];
        [self addSubview:deleteBtn];
    }
}

- (void)setIsEditing:(BOOL)editing
{
    isEditing = editing;
    if (isEditing) {
        // make the remove button visible
        [deleteBtn setHidden:NO];
        [entry setEnabled:NO];
        
        // start the wiggling animation
        CGFloat rotation = 0.03;
        CABasicAnimation *shake = [CABasicAnimation animationWithKeyPath:@"transform"];
        shake.duration = 0.13;
        shake.autoreverses = YES;
        shake.repeatCount  = MAXFLOAT;
        shake.removedOnCompletion = NO;
        shake.fromValue = [NSValue valueWithCATransform3D:CATransform3DRotate(self.layer.transform,-rotation, 0.0 ,0.0 ,1.0)];
        shake.toValue   = [NSValue valueWithCATransform3D:CATransform3DRotate(self.layer.transform, rotation, 0.0 ,0.0 ,1.0)];
        [self.layer addAnimation:shake forKey:@"shakeAnimation"];
    }
    else {
        [self.layer removeAnimationForKey:@"shakeAnimation"];
        [deleteBtn setHidden:YES];
        [entry setEnabled:YES];
    }
}

#pragma mark- private method

-(void)clickGridItem:(id)sender
{
    [delegate gridItemDidClicked:self];
}

- (void)longPressGridItem:(UILongPressGestureRecognizer*)sender
{
    switch (sender.state) {
        case UIGestureRecognizerStateBegan:
            self.pressPoint = [sender locationInView:self];
            [delegate gridItemDidEnterEditingMode:self];
            [self setAlpha:1.0];
            break;
        case UIGestureRecognizerStateEnded:
            self.pressPoint = [sender locationInView:self];
            [delegate gridItemDidEndMoved:self 
                             withLocation:self.pressPoint 
                    moveGestureRecognizer:sender];
            [self setAlpha:0.5f];
            break;
        case UIGestureRecognizerStateFailed:
            break;
        case UIGestureRecognizerStateChanged:
            [delegate gridItemDidMoved:self 
                          withLocation:self.pressPoint 
                 moveGestureRecognizer:sender];
            break;
        default:
            break;
    }
}

- (void) removeButtonClicked:(id) sender  
{
    [delegate gridItemDidDeleted:self aSection:self.section atIndex:self.index];
}

# pragma mark - Overriding UiView Methods

- (void) removeFromSuperview 
{
    [UIView animateWithDuration:0.2 animations:^{
        self.alpha = 0.0;
        [self setFrame:CGRectMake(self.frame.origin.x+50, self.frame.origin.y+50, 0, 0)];
        [deleteBtn setFrame:CGRectMake(0, 0, 0, 0)];
    }completion:^(BOOL finished) {
        [super removeFromSuperview];
    }]; 
}

@end
